<?php
class Admin_product extends Admin_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('product/product_model','product');
		$this->load->model('product/product_category_model','pcategory');				
		$this->load->model('system_config/system_config_model','system_config');	
	}
	
	public function index()
	{
		//$this->db->debug=true;
		$menu_id=12;
		$menu_name = GetMenuProperty($menu_id,'title');
		$data['menu_id'] = $menu_id;;
		$data['urlpage']="admin_product";
		$data['parameter']="?status=".@$_GET['status']."&scat_lv1=".@$_GET['scat_lv1'].'&search='.@$_GET['search'].'&page='.@$_GET['page'];		
		if(is_login()){
			if(permission($menu_id, 'canview')=='')redirect('admin');
			$data['page']= @$_GET['page'] < 1 ?  1 : $_GET['page'];
			$data['scat_lv1'] = $this->pcategory->get(FALSE,TRUE);																
			$condition= @$_GET['search']!='' ? " product_code LIKE '%".$_GET['search']."%' OR product.name LIKE '%".$_GET['search']."%' " : "1=1";
			$condition.= @$_GET['category']>0 ? " AND cat_lv1=".@$_GET['category'] : "";			
			if(@$_GET['status']!='')
			{
				 if($_GET['status']=='normal')
				 {
				 	$condition.=" AND new_status='no' AND hot_status='no'  ";
				 }else{
				 	$condition.=" AND ".@$_GET['status']." = 'yes'";
				 } 
			}
			$data['max_no'] = $this->db->getone("SELECT MAX(show_no) FROM product WHERE ".$condition);
			$data['min_no'] = $this->db->getone("SELECT MIN(show_no) FROM product WHERE ".$condition);
			//$condition .= @$_GET['type']!='' ? " AND page='".$_GET['type']."'" : "";
			$data['num_rows'] = $this->db->getone("SELECT COUNT(*) FROM product WHERE ".$condition);
			$data['result'] = $this->product->where($condition)->order_by('show_no','desc')->get();
			$data['pagination'] = $this->product->pagination();					
			$this->template->build('index',$data);
		}
		else{
			
			redirect('admin');	
		}
	}	
	function form($id=false)
	{		
		//$this->db->debug=true;
		$menu_id=12;
		$menu_name = GetMenuProperty($menu_id,'title');
		if(permission($menu_id, 'canview')=='')redirect('admin_front');
		$data['id']=$id;
		$data['parameter']="?status=".@$_GET['status']."&scat_lv1=".@$_GET['scat_lv1'].'&search='.@$_GET['search'].'&page='.@$_GET['page'];								
			$data['rs'] = @$this->product->get_row($id);										
			$data['cat_lv1'] = $this->pcategory->get(FALSE,TRUE);			
			if($id>0)
			{
				$action='View';
				$description = $action.' '.$menu_name.' : '.$data['rs']['name'];		
				save_log($menu_id,$action,$description);
			}
			$this->template->build('form',$data);		
	}
	

	
	public function ordering($mode=FALSE,$current_product_id=FALSE,$step=1,$redirect=TRUE){
		//$this->db->debug = true;
			$condition= @$_GET['search']!='' ? " product_code LIKE '%".$_GET['search']."%' OR product.name LIKE '%".$_GET['search']."%'  " : "1=1";
			$condition.= @$_GET['scat_lv1']!='' ? " AND cat_lv1=".@$_GET['scat_lv1'] : "";			
			if(@$_GET['status']!='')
			{
				 if($_GET['status']=='normal')
				 {
				 	$condition.=" AND (new_status='no' AND hot_status='no') "; 
				 }else{
				 	$condition.=" AND ".$_GET['status']."='yes' ";
				 } 
			}
			$mode = @$_GET['mode']!='' ? $_GET['mode'] : $mode; 
			$current_product_id = @$_GET['id'] > 0 ? $_GET['id'] : $current_product_id;
			
			
			switch($mode){
				case 'top':
						$current_product = $this->db->getrow("SELECT * FROM product where id=".$current_product_id);
						$update_product['id']=$current_product['id'];
						$update_product['show_no'] = $this->db->getone("SELECT (max(show_no)+1) from product");
						$this->product->save($update_product);
					break;
				case 'bottom':
						$current_product = $this->db->getrow("SELECT * FROM product where id=".$current_product_id);
						$this->db->execute("UPDATE product SET show_no=show_no+1 where id <> ".$current_product_id);
						$this->db->execute("UPDATE product SET show_no=1 where id=".$current_product_id);
					break;
				case 'up':					
					for($i=1;$i<=$step;$i++):
						$current_product = $this->db->getrow("SELECT * FROM product where id=".$current_product_id);
						$sql= " SELECT * FROM product WHERE ".$condition." AND show_no > ".$current_product['show_no']." ORDER BY show_no LIMIT 0,1 ";
						$up_product = $this->db->getrow($sql);
						if(@$up_product['id']>0){
						$update_product['id'] = $up_product['id'];
						$update_product['show_no'] = $current_product['show_no'];					
						$this->product->save($update_product);
						
						$update_product['id'] = $current_product['id'];
						$update_product['show_no'] = $up_product['show_no'];
						$this->product->save($update_product);
						}
					endfor;
					break;
				case 'down':
					for($i=1;$i<=$step;$i++):
					$current_product = $this->db->getrow("SELECT * FROM product where id=".$current_product_id);
			
					$sql= " SELECT * FROM product WHERE ".$condition." AND show_no < ".$current_product['show_no']." ORDER BY show_no DESC LIMIT 0,1 ";
					$up_product = $this->db->getrow($sql);
						if(@$up_product['id']>0){
						$update_product['id'] = $up_product['id'];
						$update_product['show_no'] = $current_product['show_no'];					
						$this->product->save($update_product);
						
						$update_product['id'] = $current_product['id'];
						$update_product['show_no'] = $up_product['show_no'];
						$this->product->save($update_product);
						}
					endfor;
					break;
			}
			if($redirect==TRUE)
			{
				redirect('admin_product?status='.@$_GET['status'].'&scat_lv1='.@$_GET['scat_lv1'].'&search='.@$_GET['search'].'&page='.@$_GET['page']);
			}
	}

	public function multi_ordering(){
			if($_POST['target_position']>0){
				if(isset($_POST['select_product'])){
					foreach($_POST['select_product'] as $key=>$item){
						if($_POST['select_product'][$key]){
							$this->order_select_target($_POST['select_product'][$key],$_POST['target_position']);
						}
					}
				}					
			}else{
				$mode=$_POST['item_action'];
				$step=$_POST['step'];
				if(isset($_POST['select_product'])){
					foreach($_POST['select_product'] as $key=>$item){
						if($_POST['select_product'][$key]){
							$this->ordering($mode,$_POST['select_product'][$key],$step,FALSE);
						}
					}
				}		
			}
			redirect('admin_product?status='.@$_GET['status'].'&scat_lv1='.@$_GET['scat_lv1'].'&search='.@$_GET['search'].'&page='.@$_GET['page']);
	}
		
	public function order_select_target($product_id,$position){
		//$this->db->debug = true;
		$sql = " SELECT * FROM product order by show_no desc limit ".($position-1).",1 ";
		$item = $this->product->get($sql,TRUE);
		foreach($item as $row):
			$target_show_no = $row['show_no'];
		endforeach;
		$curr_product = $this->product->get_row($product_id);
		if($target_show_no > $curr_product['show_no']){
			$sql = " UPDATE product set show_no = show_no - 1 where show_no >= ".$target_show_no." and show_no < ".$curr_product['show_no'];
			$this->db->Execute($sql);		
		}else{
			$sql = " UPDATE product set show_no = show_no + 1 where show_no <= ".$curr_product['show_no']." and show_no >= ".$target_show_no;
			$this->db->Execute($sql);			
		}
		$sql = " UPDATE product set show_no = ".$target_show_no." where id=".$product_id;
		$this->db->Execute($sql);
		//print_r($curr_product);		
	}
	public function save(){
		//$this->db->debug = true;	
		$menu_id=12;
		$menu_name = GetMenuProperty($menu_id,'title');
		$_POST['new_status'] = $_POST['new_status'] ==''  ? 'no' : 'yes';
		$_POST['hot_status'] = $_POST['hot_status'] ==''  ? 'no' : 'yes';
		$parameter="?status=".@$_GET['status']."&scat_lv1=".@$_GET['scat_lv1'].'&search='.@$_GET['search'].'&page='.@$_GET['page'];
		if($_POST['id']!='')
		{
			if(permission($menu_id, 'canedit')=='')redirect('admin_product');
			$action='Update';
			$description = $action.' '.$menu_name.' : '.$_POST['name'];		
			save_log($menu_id,$action,$description);
		}else{
			if(permission($menu_id, 'canadd')=='')redirect('admin_product');	
			$action='Add';
			$description = $action.' '.$menu_name.' : '.$_POST['name'];		
			save_log($menu_id,$action,$description);
		}	
		$_POST['update_date']=date("Y-m-d H:i:s");		
		if($_POST['id']<1)
		{
			$_POST['show_no'] = $this->db->getone("SELECT (max(show_no)+1) from product");
		}
		$id = $this->product->save($_POST);
				
		include('include/class.upload.php');	
		$i=1;
		if($_FILES['flproductimage_'.$i]['name']!='')
		{
					
			$productimage = $this->product->get_one("product_image_".$i,$id);

			if($productimage!='')
			{
				$productimage = explode('.',$productimage);				
				@unlink("product/".$productimage[0].'_original.'.$productimage[1]);
				@unlink("product/".$productimage[0].'_detail.'.$productimage[1]);				
				@unlink("product/".$productimage[0].'_140x140.'.$productimage[1]);	
			}
			
			$ext = pathinfo($_FILES['flproductimage_'.$i]['name'], PATHINFO_EXTENSION);
			$picname = $id."_".$i.".".$ext;
			$file_pattern =$id."_".$i;
			$uploaddir = 'product/';
			
			$this->upload_product_image($i,$uploaddir,$file_pattern,140,140);
			
			$update['id']=$id;
			$update['product_image_'.$i]=$picname;
			$this->product->save($update);			
		}			
		//set_notify('success', lang('save_data_complete'));
		redirect('admin_product/index'.$parameter);
	} 
	public function upload_product_image($index,$upload_dir,$file_pattern,$resize_width=FALSE,$resize_height=FALSE){		
			$image_file = new Upload($_FILES['flproductimage_'.$index]);
			
			$image_file->file_new_name_body = $file_pattern."_original";
			  //$image_file->image_resize = true;
			  //$foo->image_convert = jpg;
			  //$image_file->image_x = 360;
			  //$image_file->image_ratio_y = true;
			  $image_file->Process('product/');
			
			  $image_file->file_new_name_body = $file_pattern."_detail";
			  $image_file->image_resize = true;
			  //$foo->image_convert = jpg;
			  $image_file->image_x = 500;
			  $image_file->image_ratio_y = true;
			  $image_file->Process('product/');			  			 
			  
  			  $image_file->file_new_name_body = $file_pattern."_140x140";
			  $image_file->image_resize = true;
			  //$foo->image_convert = jpg;
			  $image_file->image_x = 140;
			  $image_file->image_ratio_y = true;
			  $image_file->Process('product/');
			  			  			  
			  if ($image_file->processed) {			   
			    $image_file->Clean();
			  } else {
			    echo 'error : ' . $image_file->error;
			  }
	}
	function delete($id=FALSE){
		$menu_id=12;
		$menu_name = GetMenuProperty($menu_id,'title');
		$parameter="?status=".@$_GET['status']."&scat_lv1=".@$_GET['scat_lv1']."&scat_lv2=".@$_GET['scat_lv2']."&scat_lv3=".@$_GET['scat_lv3'].'&search='.@$_GET['search'].'&page='.@$_GET['page']."&stock_not=".@$_GET['stock_not'];
		if(permission($menu_id, 'candelete')=='')redirect('admin_product/index'.$parameter);
		if($id){
			for($i=1;$i<=4;$i++)
			{
				$image = $this->product->get_one("product_image_".$i,$id);
				@unlink("product/".$image);
			}
			$data = $this->product->get_row($id);
			$action='Delete';
			$description = $action.' '.$menu_name.' : '.$data['name'];		
			save_log($menu_id,$action,$description);
			$this->product->delete($id);
			//set_notify('success', lang('delete_data_complete'));
		}
		redirect('admin_product/index'.$parameter);
	}
	public function delete_image($id=FALSE,$pindex=FALSE){
		$id = $_POST['id']=="" ? $id :$_POST['id'];
		$pindex = $_POST['pindex']=="" ? $pindex :$_POST['pindex'];
		if($id>0){
				$product = $this->product->get_row($id);
				$productimage = explode('.',$product['product_image_'.$pindex]);				
				@unlink("product/".$productimage[0].'_original.'.$productimage[1]);
				@unlink("product/".$productimage[0].'_detail.'.$productimage[1]);				
				@unlink("product/".$productimage[0].'_140x140.'.$productimage[1]);	
			$update['id'] = $id;
			$update['product_image_'.$pindex] = '';
			//$this->db->debug=true;
			$this->product->save($update);				
		}
	}
	public function reload_category_list(){
		$lv = @$_POST['lv'] > 0 ? $_POST['lv'] : 0;
		$pid = @$_POST['pid'] > 0 ? $_POST['pid'] : 0 ;
		$select = '<select name="cat_lv'.$lv.'">';
		$select .='<option value="0" >--select category--</option>';
		$result = $this->pcategory->where("pid=".$pid)->get(FALSE,TRUE);
		foreach($result as $item):
			$select.='<option value="'.$item['id'].'">'.$item['name'].'</option>';
		endforeach;	
		$select .='</select>';
		echo $select;
	}

}
?>